package com.pms.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.SqlHelper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.entity.BaseModel;
import com.pms.entity.IotCardRecharge;
import com.pms.entity.IotWaterPumpGroup;
import com.pms.entity.IotWaterPumpGroupAttr;
import com.pms.exception.RRException;
import com.pms.mapper.IotWaterPumpGroupMapper;
import com.pms.rpc.IotWaterPumpGroupService;
import com.pms.service.IIotCardRechargeService;
import com.pms.service.IIotWaterPumpGroupAttrService;
import com.pms.service.IIotWaterPumpGroupService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.pms.service.IWoGiaWpAttrService;
import com.pms.util.DateUtil;
import com.pms.utils.WoGiaFiledConstant;
import io.swagger.models.auth.In;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author asus
 * @since 2018-07-18
 */
@Service
public class IotWaterPumpGroupServiceImpl extends ServiceImpl<IotWaterPumpGroupMapper, IotWaterPumpGroup> implements IIotWaterPumpGroupService {
    protected Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    IIotCardRechargeService iotCardRechargeService;
    @Autowired
    IIotWaterPumpGroupAttrService waterPumpGroupAttrService;
    @Autowired
    IWoGiaWpAttrService woGiaWpAttrService;
    /**
     * 查询 根据 水泵房id字符串 查询 水泵组id字符串
     * @param orgIds 水泵房id字符串
     * @return 水泵组id字符串
     */
    public String getGroupIdsStrByHouseId( String orgIds){
        return baseMapper.getGroupIdsStrByHouseId(orgIds);
    }

    /**
     * 查询数据用于 机构数展示
     * @param wrapper
     * @return
     */
    public List<Map<String,Object>> selectMapList(Wrapper<IotWaterPumpGroup> wrapper){
        return baseMapper.selectMapList(wrapper);
    }

    /**
     * 查询 水泵组 实时(最新的一条)数据
     * @param page
     * @param wrapper
     * @return
     */
    public Page<Map<String,Object>> readRealTimeDataPage(Page<Map<String,Object>> page , Wrapper<Map<String,Object>> wrapper){
        SqlHelper.fillWrapper(page, wrapper);
        List<Map<String,Object>> realTimeDataList = baseMapper.readRealTimeData(page, wrapper);
        if(realTimeDataList==null){realTimeDataList = new ArrayList<Map<String,Object>>();}

        // 如果是沃佳 点位
        List<Map<String,String>> tableList = new ArrayList<Map<String,String>>();
        Map<String,Integer> tableTagMap = new HashMap<String,Integer>();

        for(int x=0,length=realTimeDataList.size();x<length;x++){
            // 如果是沃佳数据
            Integer dataSources =(Integer) realTimeDataList.get(x).get("data_source");
            if(dataSources==null){dataSources = 1;}
            if(dataSources==2){
                String group_code = (String)realTimeDataList.get(x).get("group_code");
                String[] tableName = group_code.split("\\|");
                if(tableTagMap.get(tableName[0])==null){
                    tableTagMap.put(tableName[0],0);
                    Map<String,String> readSqlParam = new HashMap<String,String>();
                    readSqlParam.put("tableNameNum",tableName[0]);
                    readSqlParam.put("tableName","`"+tableName[0]+"`"); // 纯数字的表名需要转义
                    readSqlParam.put("column","*");
                    tableList.add(readSqlParam);
                }
            }
            List<Map<String,Object>> pumpAttrList = new ArrayList<Map<String,Object>>();
            Integer count = (Integer) realTimeDataList.get(x).get("count");// 小泵数量
            if(count==null){// 无数据上报
                count=0;
                realTimeDataList.get(x).put("count",0);
            }
            try {
                String[] SBZT_arr = realTimeDataList.get(x).get("SBZT").toString().split(",");
                String[] waterFrequency_arr = realTimeDataList.get(x).get("waterFrequency").toString().split(",");
                for (int y = 0; y < count; y++) {
                    Map<String, Object> pumpAttrMap = new HashMap<String, Object>();
                    pumpAttrMap.put("pumpName", (y+1) + "号泵");
                    // 水泵频率
                    pumpAttrMap.put("pumpFrequency",waterFrequency_arr.length>y?waterFrequency_arr[y]:waterFrequency_arr[0]);
                    // 水泵运行状态
                    pumpAttrMap.put("pumpState",SBZT_arr.length>y?SBZT_arr[y]:SBZT_arr[0]);
                    pumpAttrMap.put("pumpStateName",formatPumpStateStr(pumpAttrMap.get("pumpState")+""));
                    pumpAttrList.add(pumpAttrMap);
                }
                realTimeDataList.get(x).put("pumpAttrList", pumpAttrList);
            }catch (NullPointerException ex){
                realTimeDataList.get(x).put("pumpAttrList", pumpAttrList);
                continue;
            }
        }
        // 解析 woGia 数据
        Map<String,Map<String,Object>> deviceAttrMap = getResolveWoGiaDataByTable(tableList);

        if(!deviceAttrMap.isEmpty()){
            for(Map<String,Object> devMap :realTimeDataList){
                String group_code = (String)devMap.get("group_code");
                // 判断 非 沃佳的数据处理
                Map<String,Object> group_codeAttrMap=deviceAttrMap.get(group_code);
                if(group_codeAttrMap!=null){
                    devMap.putAll(deviceAttrMap.get(group_code));
                    devMap.put("deviceStatus",0);
                }
            }
        }
        page.setRecords( realTimeDataList );
        return page;
    }
    /**
     * 查询 根据 水泵房id字符串 查询 水泵组id集合
     * @param orgIds 水泵房id字符串
     * @return 水泵组id字符串
     */
    public  List<Long> getGroupIdListByHouseId( String orgIds){
        return baseMapper.getGroupIdListByHouseId(orgIds);
    }


    /**
     * 查询社区下的小泵数量统计
     * @param paramMap
     * @return Map(communityId-社区id,totalPumpNum-总小泵数量,onlinePumpNum-在线泵数量,nolinePumpNum-离线泵数量)
     */
    public Map<String,Map<String,Object>> getPumpNumByCommunityId(Map<String,Object> paramMap){
        List<Map<String,Object>> PumpNumList = baseMapper.getPumpNumByCommunityId(paramMap);
        Map<String,Map<String,Object>> retrunMap = new HashMap<String,Map<String,Object>>();
        if(PumpNumList==null){return retrunMap; }
        for(int x=0,length=PumpNumList.size();x<length;x++){
            retrunMap.put(PumpNumList.get(x).get("communityId")+"",PumpNumList.get(x));
        }
        return retrunMap;
    }
    /**
     * 查询水泵房下的小泵数量
     * @param paramMap
     * @return Map(houseId-水泵房id,totalPumpNum-总小泵数量,onlinePumpNum-在线泵数量,nolinePumpNum-离线泵数量)
     */
    public Map<String,Map<String,Object>> getPumpNumByHouseId(Map<String,Object> paramMap){
        List<Map<String,Object>> PumpNumList = baseMapper.getPumpNumByHouseId(paramMap);
        Map<String,Map<String,Object>> retrunMap = new HashMap<String,Map<String,Object>>();
        if(PumpNumList==null){return retrunMap; }
        for(int x=0,length=PumpNumList.size();x<length;x++){
            retrunMap.put(PumpNumList.get(x).get("houseId")+"",PumpNumList.get(x));
        }
        return retrunMap;
    }

    /**
     * 查询水泵房中的水泵组
     * @param paramMap（houseId-水泵房id，communityId-小区id）
     * @return
     */
   public List<Map<String,Object>> readHousePumpGroupDetail( Map<String,Object> paramMap){
       List<Map<String,Object>> houseWaterPumpGroupList =baseMapper.readHousePumpGroupDetail(paramMap);
       if(houseWaterPumpGroupList==null){houseWaterPumpGroupList=new ArrayList<Map<String,Object>>();}
       List<Map<String,Object>> returnPumpGroupDetailList = new ArrayList<Map<String,Object>>();

       List<Map<String,Object>> woGiaPumpGroupList = new ArrayList<Map<String,Object>>();
       // 如果是沃佳 点位
       List<Map<String,String>> tableList = new ArrayList<Map<String,String>>();
       Map<String,Integer> tableTagMap = new HashMap<String,Integer>();
       for(int x=0,length=houseWaterPumpGroupList.size();x<length;x++){
           Integer dataSource =(Integer) houseWaterPumpGroupList.get(x).get("dataSource");
           if(dataSource==null){dataSource = 1;}
           if(dataSource==1){
               Long count = (Long) houseWaterPumpGroupList.get(x).get("count");// 小泵数量
               String[] SBZT_arr = houseWaterPumpGroupList.get(x).get("SBZT").toString().split(",");
               String[] waterFrequency_arr = houseWaterPumpGroupList.get(x).get("waterFrequency").toString().split(",");
               if(count > 0L){
                   for (int y = 0; y < count; y++) {
                       Map<String, Object> pumpAttrMap = new HashMap<String, Object>();
                       pumpAttrMap.put("pumpName", (y+1) + "号泵");
                       // 水泵频率
                       pumpAttrMap.put("pumpFrequency",waterFrequency_arr.length>y?waterFrequency_arr[y]:waterFrequency_arr[0]);
                       // 水泵运行状态
                       pumpAttrMap.put("pumpState",SBZT_arr.length>y?SBZT_arr[y]:SBZT_arr[0]);
                       pumpAttrMap.put("pumpStateName",formatPumpStateStr(pumpAttrMap.get("pumpState")+""));
                       pumpAttrMap.putAll(houseWaterPumpGroupList.get(x));
                       returnPumpGroupDetailList.add(pumpAttrMap);
                   }
                   continue;
               }
//            Map<String, Object> pumpAttrMap = new HashMap<String, Object>();
//            pumpAttrMap.put("pumpName", "1号泵");
//               returnPumpGroupDetailList.add(houseWaterPumpGroupList.get(x));
           }
            if(dataSource == 2){
                String group_code = (String)houseWaterPumpGroupList.get(x).get("deviceName");
                String[] tableName = group_code.split("\\|");
                if(tableTagMap.get(tableName[0])==null){
                    tableTagMap.put(tableName[0],0);
                    Map<String,String> readSqlParam = new HashMap<String,String>();
                    readSqlParam.put("tableNameNum",tableName[0]);
                    readSqlParam.put("tableName","`"+tableName[0]+"`"); // 纯数字的表名需要转义
                    readSqlParam.put("column","*");
                    tableList.add(readSqlParam);
                }
                woGiaPumpGroupList.add(houseWaterPumpGroupList.get(x));
            }
       }
       //解析 wogia  数据
       Map<String,Map<String,Object>> deviceAttrMap =getResolveWoGiaDataByTable(tableList);
       for(int x=0,len=woGiaPumpGroupList.size();x<len;x++){
            Map<String,Object> deviceAttr = deviceAttrMap.get(woGiaPumpGroupList.get(x).get("deviceName"));
            if(deviceAttr==null){deviceAttr = new HashMap<String,Object>();}
           List<Map<String,Object>> pumpAttrList = (List<Map<String,Object>>)deviceAttr.get("pumpAttrList");
            if(pumpAttrList==null){pumpAttrList = new ArrayList<Map<String,Object>>();}
            for(Map<String,Object> pumpStateMap:pumpAttrList){
                pumpStateMap.putAll(woGiaPumpGroupList.get(x));
                pumpStateMap.putAll(deviceAttr);
                pumpStateMap.remove("pumpAttrList");
                returnPumpGroupDetailList.add(pumpStateMap);
            }
//           returnPumpGroupDetailList.add(woGiaPumpGroupList.get(x));
       }
       return  returnPumpGroupDetailList;
    }
    /**
     * 查询水泵房中的水泵组
     * @param houseId  水泵房id
     * @return
     */
    public List<Map<String,Object>> readPumpGroupDetail(Long houseId){
        return baseMapper.readPumpGroupDetail(houseId);
    }


   public Page<Map<String,Object>> readDataAnalysisReportFormPage(Page<Map<String,Object>> page , Wrapper<Map<String,Object>> wrapper,Map<String,Object> paramMap){
       SqlHelper.fillWrapper(page, wrapper);
       List<Map<String,Object>> recordList = baseMapper.readPumpGroupAttrCountPressure(page,wrapper, paramMap);
       // 如果是沃佳 点位
       List<Map<String,String>> tableList = new ArrayList<Map<String,String>>();
       Map<String,Integer> tableTagMap = new HashMap<String,Integer>();
       for(int x=0,len=recordList.size();x<len;x++){
           Integer dataSource =(Integer) recordList.get(x).get("dataSource");
           if(dataSource!=null&&dataSource==2){
               String group_code = (String)recordList.get(x).get("groupCode");
               String[] tableName = group_code.split("\\|");
               if(tableTagMap.get(group_code)==null){
                   tableTagMap.put(group_code,0);
                   Map<String,String> readSqlParam = new HashMap<String,String>();
                   readSqlParam.put("tableName","`"+tableName[0]+"`"); // 纯数字的表名需要转义
                   readSqlParam.put("column","'"+group_code+"' as groupCode" +generateDataAnalysisReadCloumn(tableName[2],tableName[0]));
                   readSqlParam.put("startTime", "'"+DateUtil.format(paramMap.get("startTime"),DateUtil.DATE_PATTERN.YYYY_MM_DD_HH_MM_SS)+"'");
                   readSqlParam.put("endTime", "'"+DateUtil.format(paramMap.get("endTime"),DateUtil.DATE_PATTERN.YYYY_MM_DD_HH_MM_SS)+"'");
                   tableList.add(readSqlParam);
               }
           }
       }
       if(!tableList.isEmpty()){
           List<Map<String,Object>> deviceCountList =null;
           try {
               deviceCountList  =woGiaWpAttrService.readWogia2DataAnalysisCount(tableList);
           }catch (Exception ex){
               logger.error("查询沃佳数据报表分析，mysql查询异常");
               logger.error(ex.getMessage());
               deviceCountList = new ArrayList<Map<String,Object>>();
           }
           Map<String,Map<String,Object>> deviceCountMap = new HashMap<String,Map<String,Object>>();
           for(int x=0,len=deviceCountList.size();x<len;x++){
               deviceCountMap.put((String) deviceCountList.get(x).get("groupCode"),deviceCountList.get(x));
           }
           if(!deviceCountMap.isEmpty()){
               for(int x=0,len=recordList.size();x<len;x++){
                   Map<String,Object> recordMap =deviceCountMap.get(recordList.get(x).get("groupCode")) ;
                   if(recordMap!=null){
                       recordList.get(x).putAll(recordMap);
                   }
               }
           }
       }
       page.setRecords(recordList);
       return page;
    }

    /**
     * 0-变频运行,1-工频运行,2-未运行(停机),3-电磁阀,4-未使用,5-故障,6-检修,7-现场手动
     * @param pumpState
     * @return
     */
    public String formatPumpStateStr(String pumpState){
        if("0".equals(pumpState)){
            return "变频";
        }
        if("1".equals(pumpState)){
            return "工频";
        }
        if("2".equals(pumpState)){
            return "未运行";
        }
        if("3".equals(pumpState)){
            return "电磁阀";
        }
        if("4".equals(pumpState)){
            return "未使用";
        }
        if("5".equals(pumpState)){
            return "故障";
        }
        if("6".equals(pumpState)){
            return "检修";
        }
        return "未运行";
    }

    /**
     * 事务控制  插入水泵组
     *          水泵组充值记录
     * @param insertWaterPumpGroup
     * @param iotCardRecharge
     * @return
     */
    @Transactional(rollbackFor=Exception.class)
   public boolean  insert_insertWaterPumpGroup_cardRecharge(IotWaterPumpGroup insertWaterPumpGroup,IotCardRecharge iotCardRecharge){
        iotCardRechargeService.insert(iotCardRecharge);
        baseMapper.insert(insertWaterPumpGroup);
        return true;
    }

    /**
     * 查询 水泵组 实时(最新的一条)数据
     * @param wrapper
     * @return
     */
    public List<Map<String,Object>> readRealTimeDataList(Wrapper<Map<String,Object>> wrapper){
        List<Map<String,Object>> realTimeDataList = baseMapper.readRealTimeData(wrapper);
        if(realTimeDataList==null){realTimeDataList = new ArrayList<Map<String,Object>>();}
        return realTimeDataList;
    }

    /**
     * 根据设备名称获取消息格式化规则
     * @param name
     * @return
     */
    public JSONObject getMessageFormatRuleJson(String name){
//        String ruleJsonStr ="{\"pressureFeedback\":{\"way\":\"divide\",\"val\":\"1000\",\"remark\":\"单位换算Pa为MPa\"},\"settingPressure\":{\"way\":\"divide\",\"val\":\"1000\",\"remark\":\"单位换算Pa为MPa\"},\"waterFrequency\":{\"way\":\"divide\",\"val\":\"10\",\"remark\":\"运行频率固定取值/10\"},\"XXPL\":{\"way\":\"divide\",\"val\":\"10\",\"remark\":\"下行频率固定取值/10\"},\"ultraTightlyAlarm\":{\"way\":\"divide\",\"val\":\"1000\",\"remark\":\"单位换算Pa为MPa\"},\"SZGWYL\":{\"way\":\"divide\",\"val\":\"1000\",\"remark\":\"单位换算Pa为MPa\"},\"SBZT\":{\"way\":\"hexadecimal\",\"val\":\"2\",\"isReversal\":\"1\",\"readWay\":\"index\",\"readVal\":\"1\",\"indexJson\":{\"0\":\"0\",\"1\":\"1\",\"2\":\"0\",\"3\":\"1\",\"4\":\"0\",\"5\":\"1\",\"6\":\"0\",\"7\":\"1\",\"8\":\"0\",\"9\":\"1\",\"10\":\"0\",\"11\":\"1\",\"12\":\"0\",\"13\":\"1\",\"14\":\"2\",\"15\":\"3\",}},\"GZZT\":{\"way\":\"hexadecimal\",\"val\":\"2\",\"isReversal\":\"1\",\"readWay\":\"index\",\"readVal\":\"1\",}}";
        String ruleJsonStr ="{\"pressureFeedback\":{\"way\":\"divide\",\"val\":\"1000\",\"remark\":\"单位换算Pa为MPa\"},\"settingPressure\":{\"way\":\"divide\",\"val\":\"1000\",\"remark\":\"单位换算Pa为MPa\"},\"waterFrequency\":{\"way\":\"divide\",\"val\":\"10\",\"remark\":\"运行频率固定取值/10\"},\"XXPL\":{\"way\":\"divide\",\"val\":\"10\",\"remark\":\"下行频率固定取值/10\"},\"ultraTightlyAlarm\":{\"way\":\"divide\",\"val\":\"1000\",\"remark\":\"单位换算Pa为MPa\"},\"SZGWYL\":{\"way\":\"divide\",\"val\":\"1000\",\"remark\":\"单位换算Pa为MPa\"},\"SBZT\":{\"way\":\"hexadecimal\",\"val\":\"2\",\"isReversal\":\"1\",\"isReversal\":\"1\",\"readWay\":\"compareChar\",},\"GZZT\":{\"way\":\"hexadecimal\",\"val\":\"2\",\"isReversal\":\"1\",\"readWay\":\"index\",\"readVal\":\"1\",}}";
        JSONObject ruleJson =null;
        ruleJson = JSONObject.parseObject(ruleJsonStr);
        return ruleJson;
    }

    public Long getGroupIdByCode(String code){
        Long  GroupId =baseMapper.getGroupIdByCode(code);
        return GroupId==null?-1L:GroupId;
    }

    /**
     * 查询 水泵组 不同设备状态个数
     * @param wrapper
     * @return
     */
    public Integer selectWaterPumpStatusCount( Wrapper<Map<String,Object>> wrapper){
        return baseMapper.selectWaterPumpStatusCount(wrapper);
    }

    /*==========曲线分析==============*/
    public List<Map<String,Object>> selectReportTimesCurveMap(Map<String,Object> map){
        return baseMapper.selectReportTimesCurveMap(map);
    }
    public List<String> selectReportTimes(Map<String,Object> map){
        return baseMapper.selectReportTimes(map);
    }
    public List<Map<String,Object>> selectGroupMaps(Map<String,Object> map){
        return baseMapper.selectGroupMaps(map);
    }

    /**
     *
     * @param paramMap  请求参数
     * @return
     */
    public Map<String,Object> readDataAnalysisCurve_New(Map<String,Object> paramMap){
        Map<String,Object> returnMap = new HashMap<String,Object>();
        List<Map<String,Object>> groupNameList = baseMapper.selectGroupMaps(paramMap);
        if(groupNameList==null||groupNameList.isEmpty()){
            throw new RRException("请选择设备组",400);
        }
        List<String> reportTimeList =baseMapper.selectReportTimes(paramMap);
        if(reportTimeList==null){reportTimeList = new ArrayList<String>();}
        int reportTimeListLen = reportTimeList.size();// 时间长度数组
        Map<String,Integer> reportTimeIndexMap = new HashMap<String,Integer>();
        for(int x=0;x<reportTimeListLen;x++){
            reportTimeIndexMap.put(reportTimeList.get(x),x);
        }
        Map<String,String> groupMap = new HashMap<String,String>();// 设备组名称
        Map<String,Object[] > groupDataMap = new HashMap<String,Object[]>();// 设备组对应的数据
        for(int x=0,len=groupNameList.size();x<len;x++){
            groupMap.put((String)groupNameList.get(x).get("groupCode"),(String) groupNameList.get(x).get("groupName"));
            groupDataMap.put((String)groupNameList.get(x).get("groupCode"),new Object[reportTimeListLen]);
        }
        List<Map<String,Object>> groupDataList = baseMapper.selectReportTimesCurveMap(paramMap);
        if(groupDataList==null){
            groupDataList = new ArrayList<Map<String,Object>>();
        }
        for(int x=0,len=groupDataList.size();x<len;x++){
            Object[] dataArr = groupDataMap.get((String) groupDataList.get(x).get("deviceName"));
            if(dataArr==null){dataArr = new Object[reportTimeListLen] ;}
            Integer dataIndex = reportTimeIndexMap.get((String) groupDataList.get(x).get("reportTimeFormat"));
            dataArr[dataIndex] = groupDataList.get(x).get("value_");
            groupDataMap.put((String) groupDataList.get(x).get("deviceName"),dataArr);
        }
        returnMap.put("timeArr",reportTimeList );
        List<Map<String,Object>> returnDataList = new ArrayList<Map<String,Object>>();
        for(Map.Entry<String, String> entry : groupMap.entrySet()){
            Map<String,Object> returnDataMap =new HashMap<String,Object>();
            returnDataMap.put("groupName",entry.getValue());
            returnDataMap.put("valueArr",groupDataMap.get( entry.getKey() ));
            returnDataList.add(returnDataMap);
        }
        returnMap.put("dataArr",returnDataList);
        return returnMap;
    }

    /**
     *
     * @param paramMap
     * @param valueType 1-integer,2-double
     * @return
     */
    public Map<String,Object> readDataAnalysisCurve_New(Map<String,Object> paramMap,int valueType){
        Map<String,Object> returnMap = new HashMap<String,Object>();
        List<Map<String,Object>> returnDataList = new ArrayList<Map<String,Object>>();
        List<Map<String,Object>> groupNameList = baseMapper.selectGroupMaps(paramMap);
        if(groupNameList==null||groupNameList.isEmpty()){
            throw new RRException("请选择设备组",400);
        }
        List<String> reportTimeList =baseMapper.selectReportTimes(paramMap);
        if(reportTimeList==null){reportTimeList = new ArrayList<String>();}
        int reportTimeListLen = reportTimeList.size();// 时间长度数组
        Map<String,Integer> reportTimeIndexMap = new HashMap<String,Integer>();
        for(int x=0;x<reportTimeListLen;x++){
            reportTimeIndexMap.put(reportTimeList.get(x),x);
        }
        Map<String,String> groupMap = new HashMap<String,String>();// 设备组名称
        if(valueType==1){
            Map<String,int[] > groupDataMap = new HashMap<String,int[]>();// 设备组对应的数据
            for(int x=0,len=groupNameList.size();x<len;x++){
                groupMap.put((String)groupNameList.get(x).get("groupCode"),(String) groupNameList.get(x).get("groupName"));
                groupDataMap.put((String)groupNameList.get(x).get("groupCode"),new int[reportTimeListLen]);
            }
            List<Map<String,Object>> groupDataList = baseMapper.selectReportTimesCurveMap(paramMap);
            if(groupDataList==null){
                groupDataList = new ArrayList<Map<String,Object>>();
            }
            for(int x=0,len=groupDataList.size();x<len;x++){
                int[] dataArr = groupDataMap.get((String) groupDataList.get(x).get("deviceName"));
                if(dataArr==null){dataArr = new int[reportTimeListLen] ;}
                Integer dataIndex = reportTimeIndexMap.get((String) groupDataList.get(x).get("reportTimeFormat"));
                dataArr[dataIndex] = (Integer) groupDataList.get(x).get("value_");
                groupDataMap.put((String) groupDataList.get(x).get("deviceName"),dataArr);
            }
            returnMap.put("timeArr",reportTimeList );

            for(Map.Entry<String, String> entry : groupMap.entrySet()){
                Map<String,Object> returnDataMap =new HashMap<String,Object>();
                returnDataMap.put("groupName",entry.getValue());
                int[] valueArr = groupDataMap.get( entry.getKey() );
                returnDataMap.put("valueArr",valueArr==null? new int[reportTimeListLen]:valueArr);
                returnDataList.add(returnDataMap);
            }
        }
        if(valueType==2){
            Map<String,double[] > groupDataMap = new HashMap<String,double[]>();// 设备组对应的数据
            for(int x=0,len=groupNameList.size();x<len;x++){
                groupMap.put((String)groupNameList.get(x).get("groupCode"),(String) groupNameList.get(x).get("groupName"));
                groupDataMap.put((String)groupNameList.get(x).get("groupCode"),new double[reportTimeListLen]);
            }
            List<Map<String,Object>> groupDataList = baseMapper.selectReportTimesCurveMap(paramMap);
            if(groupDataList==null){
                groupDataList = new ArrayList<Map<String,Object>>();
            }
            for(int x=0,len=groupDataList.size();x<len;x++){
                double[] dataArr = groupDataMap.get((String) groupDataList.get(x).get("deviceName"));
                if(dataArr==null){dataArr = new double[reportTimeListLen] ;}
                Integer dataIndex = reportTimeIndexMap.get((String) groupDataList.get(x).get("reportTimeFormat"));
                dataArr[dataIndex] = (Double) groupDataList.get(x).get("value_");
                groupDataMap.put((String) groupDataList.get(x).get("deviceName"),dataArr);
            }
            returnMap.put("timeArr",reportTimeList );
            for(Map.Entry<String, String> entry : groupMap.entrySet()){
                Map<String,Object> returnDataMap =new HashMap<String,Object>();
                returnDataMap.put("groupName",entry.getValue());
                double[] valueArr = groupDataMap.get( entry.getKey() );
                returnDataMap.put("valueArr",valueArr==null? new double[reportTimeListLen]:valueArr);
                returnDataList.add(returnDataMap);
            }
        }
        returnMap.put("dataArr",returnDataList);
        return returnMap;
    }

    /**
     *
     * @param paramMap
     * @param valueType 2-多组x轴(时间序列不一致)对多组y轴,3 多组x轴(时间序列一致)对多组y轴
     * @return
     */
    public List<Map<String,Object>> readDataAnalysisCurve(Map<String,Object> paramMap,Integer valueType){
        List<Map<String,Object>> returnDataMapList = new ArrayList<Map<String,Object>>();
        if(valueType==null||valueType<2){
            returnDataMapList = baseMapper.readDataAnalysisCurve(paramMap);
            return returnDataMapList;
        }
        if(valueType==2){
            List<Map<String,Object>> groupNameList = baseMapper.selectGroupMaps(paramMap);// 查询呢设备组
            if(groupNameList==null||groupNameList.isEmpty()){
                throw new RRException("请选择设备组",400);
            }
            Map<String,String > groupMap = new HashMap<String,String>();// 设备组对应的数据
            Map<String,List<JSONArray>> groupDataMap = new HashMap<String,List<JSONArray>>();// 设备组对应的数据
            for(int x=0,len=groupNameList.size();x<len;x++){
                groupMap.put((String)groupNameList.get(x).get("groupCode"),(String) groupNameList.get(x).get("groupName"));
                groupDataMap.put((String)groupNameList.get(x).get("groupCode"),new ArrayList<JSONArray>());
            }
            List<Map<String,Object>> groupDataList = baseMapper.selectReportTimesCurveMap(paramMap);
            if(groupDataList==null){
                groupDataList = new ArrayList<Map<String,Object>>();
            }
            for(int x=0,len=groupDataList.size();x<len;x++){
                List<JSONArray> dataArr = groupDataMap.get((String) groupDataList.get(x).get("deviceName"));
                if(dataArr==null){dataArr =new ArrayList<JSONArray>();}
                StringBuilder jsonArrayBuilder = new StringBuilder("[");
                jsonArrayBuilder.append("'").append(groupDataList.get(x).get("reportTimeFormat")).append("'");// 拼接时间
                jsonArrayBuilder.append(",").append(groupDataList.get(x).get("value_"));// 拼接时间
                jsonArrayBuilder.append("]");
                dataArr.add(JSONArray.parseArray(jsonArrayBuilder.toString()));
                groupDataMap.put((String) groupDataList.get(x).get("deviceName"),dataArr);
            }
            for(Map.Entry<String, String> entry : groupMap.entrySet()){
                Map<String,Object> returnDataMap =new HashMap<String,Object>();
                returnDataMap.put("groupName",entry.getValue());
                returnDataMap.put("valueArr",groupDataMap.get( entry.getKey() ));
                returnDataMapList.add(returnDataMap);
            }
        }
        if(valueType==3){
             /*======= 查询 设备组 数据上报时间序列  ==*/
            List<Map<String,Object>> groupNameList = baseMapper.selectGroupMaps(paramMap);// 查询呢设备组,返回 groupName,groupCode,dataSource
            if(groupNameList==null||groupNameList.isEmpty()){
                throw new RRException("请选择设备组",400);
            }
            Map<String,String > groupMap = new HashMap<String,String>();// 设备组对应的数据
            List<String> groupCodeList = new ArrayList<String>();

            //沃佳 设备编号 集合
             List<String> woGiaDeviceNameList = new ArrayList<String>();
            for(int x=0,len=groupNameList.size();x<len;x++){
                String groupCode = (String)groupNameList.get(x).get("groupCode");
                groupMap.put(groupCode,(String) groupNameList.get(x).get("groupName"));
                groupCodeList.add(groupCode);
                Integer dataSource = (Integer) groupNameList.get(x).get("dataSource");
                if(dataSource!=null&&dataSource==2){
                    woGiaDeviceNameList.add(groupCode);
                }
            }
            /*  查询沃佳数据
            1) 验证设备属性表 中 曲线查询字段是否存在
            2)查询设备的时间序列

             */
            // 监控参数 (1-电流,2-电压,3-进水压力,4-出水压力,5-进水瞬时流量,6-出水瞬时流量)
            Integer monitorParam = (Integer) paramMap.get("monitorParam");
            String startDateStr =DateUtil.format(paramMap.get("startTime"),DateUtil.DATE_PATTERN.YYYY_MM_DD_HH_MM_SS);
            String endDateStr =DateUtil.format(paramMap.get("endTime"),DateUtil.DATE_PATTERN.YYYY_MM_DD_HH_MM_SS);
            String readWoGiaCurveColumn = null;
            if(monitorParam!= null){
                if(monitorParam == 3){
                    readWoGiaCurveColumn =WoGiaFiledConstant.INLET_PRESSURE;
                }
                if(monitorParam == 4){
                    readWoGiaCurveColumn =WoGiaFiledConstant.OUT_PRESSURE;
                }
            }
            List<Map<String,String>> woGiaSelectMapList = new ArrayList<Map<String,String>>();
            if(!woGiaDeviceNameList.isEmpty()){
               Map<String,List<String>> wogiaDeviceAttrTableNameMap = new HashMap<String,List<String>>();
                for(String woGiaDeviceName : woGiaDeviceNameList){
                    String[] woGiaDeviceNameSplit = woGiaDeviceName.split("\\|");
                    List<String> columnNameList=wogiaDeviceAttrTableNameMap.get(woGiaDeviceNameSplit[0]);
                    if(columnNameList==null){
                        Map<String,String> cloumnParamMap = new HashMap<String,String>();
                        cloumnParamMap.put("tablename",woGiaDeviceNameSplit[0]);
                        cloumnParamMap.put("columnPrifix",readWoGiaCurveColumn);
                        columnNameList=woGiaWpAttrService.selectAllColumnByTableName(cloumnParamMap);
                        wogiaDeviceAttrTableNameMap.put(woGiaDeviceNameSplit[0],columnNameList);
                        if(columnNameList.contains(woGiaDeviceNameSplit[2]+readWoGiaCurveColumn)){
                            Map<String,String> woGiaSelectMap = new HashMap<String,String>();
                            woGiaSelectMap.put("tableName","`"+woGiaDeviceNameSplit[0]+"`");
                            woGiaSelectMap.put("column","'"+woGiaDeviceName+"' as deviceName,Time as reportTimeFormat,FORMAT("+woGiaDeviceNameSplit[2]+readWoGiaCurveColumn+",2) as value_");
                            woGiaSelectMap.put("startTime","'"+startDateStr+"'");
                            woGiaSelectMap.put("endTime","'"+endDateStr+"'");
                            woGiaSelectMapList.add(woGiaSelectMap);
                        }
                    }else{
                       if(columnNameList.contains(woGiaDeviceNameSplit[2]+readWoGiaCurveColumn)){
                            Map<String,String> woGiaSelectMap = new HashMap<String,String>();
                            woGiaSelectMap.put("tableName","`"+woGiaDeviceNameSplit[0]+"`");
                           woGiaSelectMap.put("column","'"+woGiaDeviceName+"' as deviceName,Time as reportTimeFormat,FORMAT("+woGiaDeviceNameSplit[2]+readWoGiaCurveColumn+",2) as value_");
                           woGiaSelectMap.put("startTime","'"+startDateStr+"'");
                           woGiaSelectMap.put("endTime","'"+endDateStr+"'");
                            woGiaSelectMapList.add(woGiaSelectMap);
                        }
                    }
                }
            }


            /*======= 查询 设备组 数据上报时间序列  ==*/

            List<String> reportTimeList =baseMapper.selectReportTimes(paramMap);
            if(reportTimeList==null){reportTimeList = new ArrayList<String>();}
            if(!woGiaSelectMapList.isEmpty()){
                LinkedHashSet<String> woGiaReportTimeList =woGiaWpAttrService.readWogia2DataAnalysisCurveTime(woGiaSelectMapList);
                if(woGiaReportTimeList==null){woGiaReportTimeList = new LinkedHashSet<String>();}
                reportTimeList.addAll(woGiaReportTimeList);
                Collections.sort(reportTimeList);//默认排序(从小到大)
            }

            /*======= 查询 设备组 数据  ==*/
            Map<String,Map<String,Object>> dataMap = new HashMap<String,Map<String,Object>>();
            if(!reportTimeList.isEmpty()){
                List<Map<String,Object>> groupDataList = baseMapper.selectReportTimesCurveMap(paramMap);
                if(groupDataList==null){
                    groupDataList = new ArrayList<Map<String,Object>>();
                }
                if(!woGiaSelectMapList.isEmpty()){
                    List<Map<String,Object>> woGiaGroupDataList = woGiaWpAttrService.readWogia2DataAnalysisCount(woGiaSelectMapList);
                    groupDataList.addAll(woGiaGroupDataList==null?new ArrayList<>():woGiaGroupDataList);
                }
                for(int x=0,len=groupDataList.size();x<len;x++){
                    // 根据 设备编号+ 时间  存储数据
                    dataMap.put(groupDataList.get(x).get("deviceName")+"|"+groupDataList.get(x).get("reportTimeFormat"),groupDataList.get(x));
                }
            }

            Map<String,List<JSONArray>> groupDataMap = new HashMap<String,List<JSONArray>>();// 设备组对应的数据
            for(int y=0,len = groupCodeList.size();y<len;y++){// 遍历 设备编号
                Map<String,Object> returnDataMap =new HashMap<String,Object>();
                returnDataMap.put("groupName", groupMap.get(groupCodeList.get(y)) );
                List<JSONArray> dataArr = new ArrayList<JSONArray>();
                for(int x=0,reportTimeLen = reportTimeList.size();x<reportTimeLen;x++){// 遍历时间轴
                    Map<String,Object> data = dataMap.get( groupCodeList.get(y)+"|"+ reportTimeList.get(x));
                    if(data==null||data.isEmpty()){
                        StringBuilder jsonArrayBuilder = new StringBuilder("[");
                        jsonArrayBuilder.append("'").append( reportTimeList.get(x) ).append("'");// 拼接时间
                        jsonArrayBuilder.append(",").append("null");
                        jsonArrayBuilder.append("]");
                        dataArr.add(JSONArray.parseArray(jsonArrayBuilder.toString()));
                    }else{
                        StringBuilder jsonArrayBuilder = new StringBuilder("[");
                        jsonArrayBuilder.append("'").append( reportTimeList.get(x) ).append("'");// 拼接时间
                        jsonArrayBuilder.append(",").append(data.get("value_"));
                        jsonArrayBuilder.append("]");
                        dataArr.add(JSONArray.parseArray(jsonArrayBuilder.toString()));
                    }
                }
                returnDataMap.put("valueArr",dataArr);
                returnDataMapList.add(returnDataMap);
            }
        }
        return returnDataMapList;
    }

    @Override
    public void generateWoGiaPumpNumRecord() {
        List<String> tableNameList = woGiaWpAttrService.readWogia2TableNameList();
        Map<String,Integer> deviceAttrMap = new HashMap<String,Integer>();
        for(String tableName:tableNameList){
            Map<String,String> readSqlParam = new HashMap<String,String>();
            readSqlParam.put("tableName","`"+tableName+"`"); // 纯数字的表名需要转义
            readSqlParam.put("column","*");
            Map<String,Object> woGiaWpAttrMap= null;
            try {
                woGiaWpAttrMap =woGiaWpAttrService.readRealTimeDeviceData(readSqlParam);
            }catch (Exception ex){
                ex.printStackTrace();
                continue;
            }
            for(Map.Entry<String, Object> entry : woGiaWpAttrMap.entrySet()) {
                String columnPrefix = entry.getKey().substring(0, 1);
                String key =  tableName+ "|device|" + columnPrefix;
                Integer value = deviceAttrMap.get(key);
                if (value == null) {
                    value = 0;
                }
                String columnSuffix = entry.getKey().substring(1);
                if (WoGiaFiledConstant.PUMP_SIGNAL_ONE.equals(columnSuffix)) { //1号泵运行状态
                    value = value+1;
                    deviceAttrMap.put(key, value);
                    continue;
                }
                if (WoGiaFiledConstant.PUMP_SIGNAL_TWO.equals(columnSuffix)) { //2号泵运行状态
                    value = value+1;
                    deviceAttrMap.put(key, value);
                    continue;
                }
                if (WoGiaFiledConstant.PUMP_SIGNAL_THREE.equals(columnSuffix)) { //3号泵运行状态
                    value = value+1;
                    deviceAttrMap.put(key, value);
                    continue;
                }
                if (WoGiaFiledConstant.PUMP_SIGNAL_FOUR.equals(columnSuffix)) { //4号泵运行状态
                    value = value+1;
                    deviceAttrMap.put(key, value);
                    continue;
                }
                if (WoGiaFiledConstant.PUMP_SIGNAL_FIVE.equals(columnSuffix)) { //5号泵运行状态
                    value = value+1;
                    deviceAttrMap.put(key, value);
                    continue;
                }
                if (WoGiaFiledConstant.PUMP_SIGNAL_SIX.equals(columnSuffix)) { //6号泵运行状态
                    value = value+1;
                    deviceAttrMap.put(key, value);
                    continue;
                }
            }
        }
        List<IotWaterPumpGroupAttr> insertPumpNumList = new ArrayList<IotWaterPumpGroupAttr>();
        Long nowDate = new Date().getTime();
       for(Map.Entry<String, Integer> entry : deviceAttrMap.entrySet()){
           IotWaterPumpGroupAttr insertPumpNum = new IotWaterPumpGroupAttr();
           insertPumpNum.setWaterPumpGroupId(BaseModel.returnStaticIdLong());
           insertPumpNum.setCount( entry.getValue() );
           insertPumpNum.setReportTime(nowDate);
           insertPumpNum.setDeviceStatus(0);
           insertPumpNum.setDeviceName(entry.getKey());
           insertPumpNumList.add(insertPumpNum);
       }
       if(!insertPumpNumList.isEmpty()){
           waterPumpGroupAttrService.insertBatch(insertPumpNumList);
       }
    }

    public Map<String,Map<String,Object>> getResolveWoGiaDataByTable(List<Map<String,String>> tableList) {
        Map<String,Map<String,Object>> deviceAttrMap = new HashMap<String,Map<String,Object>>();
        for(Map<String,String> tableMap:tableList){
            Map<String,Object> woGiaWpAttrMap= woGiaWpAttrService.readRealTimeDeviceData(tableMap);
            for(Map.Entry<String, Object> entry : woGiaWpAttrMap.entrySet()){
                String columnPrefix = entry.getKey().substring(0,1);
                String key = tableMap.get("tableNameNum")+"|device|"+columnPrefix;
                Map<String,Object> value = deviceAttrMap.get(key);
                if(value==null){value=new HashMap<String,Object>();}
                String columnSuffix = entry.getKey().substring(1);
                if(WoGiaFiledConstant.INLET_PRESSURE.equals(columnSuffix)) {//进水压力
                    value.put("SZGWYL", formatDoubleData(entry.getValue()));
                    deviceAttrMap.put(key,value);
                    continue;
                }
                if(WoGiaFiledConstant.SET_PRESSURE.equals(columnSuffix) ){  //额定压力
                    value.put("settingPressure", formatDoubleData(entry.getValue()));
                    deviceAttrMap.put(key,value);
                    continue;
                }
                if(WoGiaFiledConstant.OUT_PRESSURE.equals(columnSuffix) ){ //出水压力
                    value.put("pressureFeedback",formatDoubleData(entry.getValue()));
                    deviceAttrMap.put(key,value);
                    continue;
                }
                if(WoGiaFiledConstant.FREQUENCY_CONVERTER_ONE.equals(columnSuffix) ){ //频率
                    value.put("waterFrequency",formatDoubleData(entry.getValue()));
                    deviceAttrMap.put(key,value);
                    continue;
                }
                if(WoGiaFiledConstant.OUTLET_PRESSURE_SUPER_HIGH.equals(columnSuffix) ){ //超压超高
                    String pressureValueStr = entry.getValue().toString();
                    double pressureValue =Double.parseDouble(pressureValueStr);
                    if(pressureValue>0){// 压力超高 后,设置超压报警的值
                        value.put("ultraTightlyAlarm",formatDoubleData(woGiaWpAttrMap.get(columnPrefix+columnSuffix)));
                    }
                    deviceAttrMap.put(key,value);
                    continue;
                }
                if(WoGiaFiledConstant.AUTO.equals(columnSuffix) ){ //自动
                    value.put("GZZT","0,1");// 0-自动运行,1-变频运行
                    deviceAttrMap.put(key,value);
                    continue;
                }
                if(WoGiaFiledConstant.MANUAL.equals(columnSuffix) ){ //手动
                    value.put("GZZT","1");
                    deviceAttrMap.put(key,value);
                    continue;
                }
                if(WoGiaFiledConstant.PUMP_SIGNAL_ONE.equals(columnSuffix) ){ //1号泵运行状态
                    List<Map<String,Object>> pumpAttrList = (List<Map<String,Object>>)value.get("pumpAttrList");
                    if(pumpAttrList==null){pumpAttrList=new ArrayList<Map<String,Object>>();}
                    Map<String, Object> pumpAttrMap =woGiaWpAttrService.generatePumpState(1,entry.getValue());
                    Object  pumpFrequency = woGiaWpAttrMap.get(columnPrefix+WoGiaFiledConstant.FREQUENCY_CONVERTER_ONE);
                    pumpAttrMap.put("pumpFrequency",formatDoubleData(pumpFrequency));
                    pumpAttrMap.put("deviceKey",key);
                    pumpAttrList.add( pumpAttrMap );
                    value.put("pumpAttrList",pumpAttrList);
                    value.put("count",pumpAttrList.size());
                    deviceAttrMap.put(key,value);
                    continue;
                }
                if(WoGiaFiledConstant.PUMP_SIGNAL_TWO.equals(columnSuffix) ){ //2号泵运行状态
                    List<Map<String,Object>> pumpAttrList = (List<Map<String,Object>>)value.get("pumpAttrList");
                    if(pumpAttrList==null){pumpAttrList=new ArrayList<Map<String,Object>>();}
                    Map<String, Object> pumpAttrMap =woGiaWpAttrService.generatePumpState(2,entry.getValue());
                    Object  pumpFrequency = woGiaWpAttrMap.get(columnPrefix+WoGiaFiledConstant.FREQUENCY_CONVERTER_TWO);
                    if(pumpFrequency==null){
                        pumpFrequency = woGiaWpAttrMap.get(columnPrefix+WoGiaFiledConstant.FREQUENCY_CONVERTER_ONE);
                    }
                    pumpAttrMap.put("deviceKey",key);
                    pumpAttrMap.put("pumpFrequency",formatDoubleData(pumpFrequency));
                    pumpAttrList.add( pumpAttrMap );
                    value.put("pumpAttrList",pumpAttrList);
                    value.put("count",pumpAttrList.size());
                    deviceAttrMap.put(key,value);
                    continue;
                }
                if(WoGiaFiledConstant.PUMP_SIGNAL_THREE.equals(columnSuffix) ){ //3号泵运行状态
                    List<Map<String,Object>> pumpAttrList = (List<Map<String,Object>>)value.get("pumpAttrList");
                    if(pumpAttrList==null){pumpAttrList=new ArrayList<Map<String,Object>>();}
                    Map<String, Object> pumpAttrMap =woGiaWpAttrService.generatePumpState(3,entry.getValue());
                    Object  pumpFrequency = woGiaWpAttrMap.get(columnPrefix+WoGiaFiledConstant.FREQUENCY_CONVERTER_THREE);
                    if(pumpFrequency==null){
                        pumpFrequency = woGiaWpAttrMap.get(columnPrefix+WoGiaFiledConstant.FREQUENCY_CONVERTER_ONE);
                    }
                    pumpAttrMap.put("deviceKey",key);
                    pumpAttrMap.put("pumpFrequency",formatDoubleData(pumpFrequency));
                    pumpAttrList.add( pumpAttrMap );
                    value.put("pumpAttrList",pumpAttrList);
                    value.put("count",pumpAttrList.size());
                    deviceAttrMap.put(key,value);
                    continue;
                }
                if(WoGiaFiledConstant.PUMP_SIGNAL_FOUR.equals(columnSuffix) ){ //4号泵运行状态
                    List<Map<String,Object>> pumpAttrList = (List<Map<String,Object>>)value.get("pumpAttrList");
                    if(pumpAttrList==null){pumpAttrList=new ArrayList<Map<String,Object>>();}
                    Map<String, Object> pumpAttrMap =woGiaWpAttrService.generatePumpState(4,entry.getValue());
                    Object  pumpFrequency = woGiaWpAttrMap.get(columnPrefix+WoGiaFiledConstant.FREQUENCY_CONVERTER_FOUR);
                    if(pumpFrequency==null){
                        pumpFrequency = woGiaWpAttrMap.get(columnPrefix+WoGiaFiledConstant.FREQUENCY_CONVERTER_ONE);
                    }
                    pumpAttrMap.put("deviceKey",key);
                    pumpAttrMap.put("pumpFrequency",formatDoubleData(pumpFrequency));
                    pumpAttrList.add( pumpAttrMap );
                    value.put("pumpAttrList",pumpAttrList);
                    value.put("count",pumpAttrList.size());
                    deviceAttrMap.put(key,value);
                    continue;
                }
                if(WoGiaFiledConstant.PUMP_SIGNAL_FIVE.equals(columnSuffix) ){ //5号泵运行状态
                    List<Map<String,Object>> pumpAttrList = (List<Map<String,Object>>)value.get("pumpAttrList");
                    if(pumpAttrList==null){pumpAttrList=new ArrayList<Map<String,Object>>();}
                    Map<String, Object> pumpAttrMap =woGiaWpAttrService.generatePumpState(5,entry.getValue());
                    Object  pumpFrequency = woGiaWpAttrMap.get(columnPrefix+WoGiaFiledConstant.FREQUENCY_CONVERTER_FIVE);
                    if(pumpFrequency==null){
                        pumpFrequency = woGiaWpAttrMap.get(columnPrefix+WoGiaFiledConstant.FREQUENCY_CONVERTER_ONE);
                    }
                    pumpAttrMap.put("deviceKey",key);
                    pumpAttrMap.put("pumpFrequency",formatDoubleData(pumpFrequency));
                    pumpAttrList.add( pumpAttrMap );
                    value.put("pumpAttrList",pumpAttrList);
                    value.put("count",pumpAttrList.size());
                    deviceAttrMap.put(key,value);
                    continue;
                }
                if(WoGiaFiledConstant.PUMP_SIGNAL_SIX.equals(columnSuffix) ){ //6号泵运行状态
                    List<Map<String,Object>> pumpAttrList = (List<Map<String,Object>>)value.get("pumpAttrList");
                    if(pumpAttrList==null){pumpAttrList=new ArrayList<Map<String,Object>>();}
                    Map<String, Object> pumpAttrMap =woGiaWpAttrService.generatePumpState(6,entry.getValue());
                    Object  pumpFrequency = woGiaWpAttrMap.get(columnPrefix+WoGiaFiledConstant.FREQUENCY_CONVERTER_SIX);
                    if(pumpFrequency==null){
                        pumpFrequency = woGiaWpAttrMap.get(columnPrefix+WoGiaFiledConstant.FREQUENCY_CONVERTER_ONE);
                    }
                    pumpAttrMap.put("deviceKey",key);
                    pumpAttrMap.put("pumpFrequency",formatDoubleData(pumpFrequency));
                    pumpAttrList.add( pumpAttrMap );
                    value.put("pumpAttrList",pumpAttrList);
                    value.put("count",pumpAttrList.size());
                    deviceAttrMap.put(key,value);
                    continue;
                }
            }// 表中最新数据 的 列
        }// 循环表

        return deviceAttrMap;
    }

    /**
     *
     * @param cloumnPrefix 查询类前缀
     * @return
     */
    public String generateDataAnalysisReadCloumn(String cloumnPrefix,String tableName){
        if(StringUtils.isBlank(cloumnPrefix)){
            return "*";
        }
        Map<String,String> cloumnParamMap = new HashMap<String,String>();
        cloumnParamMap.put("tablename",tableName);
        cloumnParamMap.put("columnPrifix",cloumnPrefix);
        List<String> columnNameList=woGiaWpAttrService.selectAllColumnByTableName(cloumnParamMap);
        StringBuffer readCloumn = new StringBuffer(100);
        String SZGWYL_columnName = cloumnPrefix+WoGiaFiledConstant.INLET_PRESSURE;
        if(columnNameList.contains(SZGWYL_columnName)){
            readCloumn.append(",").append("FORMAT(MAX(").append(SZGWYL_columnName).append("),2) as maxSZGWYL");
            readCloumn.append(",").append("FORMAT(MIN(").append(SZGWYL_columnName).append("),2) as minSZGWYL");
            readCloumn.append(",").append("FORMAT(AVG(").append(SZGWYL_columnName).append("),2) as avgSZGWYL");
        }else{
            readCloumn.append(",").append("0.0 as maxSZGWYL");
            readCloumn.append(",").append("0.0 as minSZGWYL");
            readCloumn.append(",").append("0.0 as avgSZGWYL");
        }
        //出水压力
        String PressureFeedback_columnName = cloumnPrefix+WoGiaFiledConstant.OUT_PRESSURE;
        if(columnNameList.contains(PressureFeedback_columnName)){
            readCloumn.append(",").append("FORMAT(MAX(").append(PressureFeedback_columnName).append("),2) as maxPressureFeedback");
            readCloumn.append(",").append("FORMAT(MIN(").append(PressureFeedback_columnName).append("),2) as minPressureFeedback");
            readCloumn.append(",").append("FORMAT(AVG(").append(PressureFeedback_columnName).append("),2) as avgPressureFeedback");
        }else{
            readCloumn.append(",").append("0.0 as maxPressureFeedback");
            readCloumn.append(",").append("0.0 as minPressureFeedback");
            readCloumn.append(",").append("0.0 as avgPressureFeedback");
        }
       //额定压力
        String SettingPressure_columnName = cloumnPrefix+WoGiaFiledConstant.SET_PRESSURE;
        if(columnNameList.contains(SettingPressure_columnName)) {
            readCloumn.append(",").append("FORMAT(MAX(").append(SettingPressure_columnName).append("),2) as maxSettingPressure");
            readCloumn.append(",").append("FORMAT(MIN(").append(SettingPressure_columnName).append("),2) as minSettingPressure");
            readCloumn.append(",").append("FORMAT(AVG(").append(SettingPressure_columnName).append("),2) as avgSettingPressure");
        }else {
            readCloumn.append(",").append("0.0 as maxSettingPressure");
            readCloumn.append(",").append("0.0 as minSettingPressure");
            readCloumn.append(",").append("0.0 as avgSettingPressure");
        }
        return readCloumn.toString();
    }

    public static Object formatDoubleData(Object obj){
        if(obj instanceof Double){
            BigDecimal bg = new BigDecimal((Double)obj);
            obj = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        if(obj instanceof Float){
            BigDecimal bg =  new BigDecimal(String.valueOf(obj));
            obj = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        }
        return obj;
    }
}
